﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FrienDev.Api;
using System.Net.Mail;
using FrienDev.Data;
using System.Data.Linq;
using System.Web;
using System.IO;

namespace FrienDev.BusinessRules
{
    public class ApiHelper : IApiHelper
    {
        public static ApiHelper Instance = new ApiHelper();

        private FrienDevDataContext m_DataContext = FrienDevDataContext.Instance;

        private ApiHelper()
        {
        }

        public bool IsFriendsPage()
        {
            string requestUserId = GetRequestUserId();
            if (requestUserId != "")
            {
                return true;
            }
            return false;
        }

        public string GetRequestUserId()
        {
            if (HttpContext.Current.Request["uid"] != null)
            {
                return HttpContext.Current.Request["uid"].ToString();
            }
            return "";
        }

        public string GetUserLogoUrl(string userId)
        {
            string str = "/upload/logo/s/" + userId + ".png";
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "upload\\logo\\s\\" + userId + ".png"))
            {
                return str;
            }
            else
            {
                return "/upload/logo/s/default.gif";
            }
        }

        public string GetUserBigLogoUrl(string userId)
        {
            string str = "/upload/logo/b/" + userId + ".png";
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "upload\\logo\\b\\" + userId + ".png"))
            {
                return str;
            }
            else
            {
                return "/upload/logo/b/default.gif";
            }
        }

        /// <summary>
        /// 得到用户的权限设置
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="privacytype"></param>
        /// <returns></returns>
        public string GetUserPrivacySetting(string userid, string privacytype)
        {
            User user = UserRules.Instance.GetUserByUserId(userid);
            if (!string.IsNullOrEmpty(user.PrivacySettings))
            {
                string res = "";
                string[] ps = user.PrivacySettings.Split('-');
                switch (privacytype)
                {
                    case "DefaultPage":
                        res = ps[0];
                        break;
                    case "RecentVistList":
                        res = ps[1];
                        break;
                    case "FriendsList":
                        res = ps[2];
                        break;
                    case "ProfileBasicInfo":
                        res = ps[3];
                        break;
                    case "ProfileDetailInfo":
                        res = ps[4];
                        break;
                    case "MSN":
                        res = ps[5];
                        break;
                    case "QQ":
                        res = ps[6];
                        break;
                    case "Telephone":
                        res = ps[7];
                        break;
                    case "MobilePhone":
                        res = ps[8];
                        break;
                    case "Fax":
                        res = ps[9];
                        break;
                    case "Track":
                        res = ps[10];
                        break;
                    default:
                        res = "";
                        break;
                }
                return res.Trim(); ;
            }
            else
            {
                return "";
            }
        }

        /// <summary>
        ///  判断对象是否显示
        /// </summary>
        /// <param name="curuserid"></param>
        /// <param name="curfriendid"></param>
        /// <param name="typename"></param>
        /// <returns></returns>
        public bool IsVisible(string curuserid, string curfriendid, string typename)
        {
            string ps = ApiHelper.Instance.GetUserPrivacySetting(curfriendid, typename.Trim());
            if (!string.IsNullOrEmpty(ps))
            {
                if (ps == "0")
                {
                    return false;
                }
                else if (ps == "1")
                {
                    if (FriendRules.Instance.IsFriend(curuserid, curfriendid) || curuserid == curfriendid)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return true;
            }
        }

        /// <summary>
        /// 发送系统消息
        /// </summary>
        /// <param name="SystemName"></param>
        /// <param name="RequestType"></param>
        /// <param name="SenderId"></param>
        /// <param name="SenderName"></param>
        /// <param name="ReceiverId"></param>
        /// <param name="parameters"></param>
        public void SendSystemMessage(string systemName, string requestType, string receiverId, string[] parameters)
        {
            string MessageContent;
            StringBuilder sbMessageContent = new StringBuilder();
            sbMessageContent.Append(systemName);
            sbMessageContent.Append("#####");
            sbMessageContent.Append(requestType);
            //sbMessageContent.Append("#####");
            //sbMessageContent.Append(DateTime.Now.ToString());
            sbMessageContent.Append("#####");
            for (int i = 0; i < parameters.Length; i++)
            {
                sbMessageContent.Append(parameters[i]);
                if (i < parameters.Length - 1)
                {
                    sbMessageContent.Append("#####");
                }
            }
            MessageContent = sbMessageContent.ToString();
            MessageRules.Instance.SendSystemMessage(DateTime.Now, receiverId, MessageContent);

        }


        public void ChangeSystemMessageRequestType(int messageId, string targetType)
        {
            MessageRules.Instance.ChangeSystemMessageRequestType(messageId, targetType);
        }

        #region IApiHelper Members

        /// <summary>
        /// 添加一条新的动态
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="source"></param>
        /// <param name="type"></param>
        /// <param name="parameters"></param>
        public void AddTrack(string userId, Type source, int type, string[] parameters)
        {
            UserApplication userApp = ApplicationRules.Instance.GetCurrentUserApplicationByUserIdAndType(userId, source);
            AddTrack(userApp, type, parameters);
        }

        public void AddTrack(UserApplication userApp, int type, string[] parameters)
        {
            string content = string.Join("#####", parameters);
            Track track = new Track();
            track.TrackContent = content;
            track.TrackDateTime = DateTime.Now;
            track.TrackType = type;
            track.UserApplication = userApp;
            m_DataContext.Tracks.InsertOnSubmit(track);
            m_DataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
        }

        /// <summary>
        /// 在今天的同一种动态参数后面添加参数，如果还没有，则添加一条新动态
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="source"></param>
        /// <param name="type"></param>
        /// <param name="parameters"></param>
        public void AppendTodayTrack(string userId, Type source, int type, string[] parameters)
        {
            UserApplication userApp = ApplicationRules.Instance.GetCurrentUserApplicationByUserIdAndType(userId, source);
            IEnumerable<Track> tracks = from t in m_DataContext.Tracks
                                        where t.UserApplication == userApp && t.TrackType == type && t.TrackDateTime.Date == DateTime.Now.Date
                                        select t;
            Track track = tracks.SingleOrDefault();
            if (track == null)
            {
                AddTrack(userApp, type, parameters);
            }
            else
            {
                string newContent = string.Join("#####", parameters);
                track.TrackContent = string.Concat(newContent, "#####", track.TrackContent);
                m_DataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
        }

        /// <summary>
        /// 更新今天的同一种动态的参数，如果还没有，则添加一条新动态
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="source"></param>
        /// <param name="type"></param>
        /// <param name="parameters"></param>
        public void UpdateTodayTrack(string userId, Type source, int type, string[] parameters)
        {
            UserApplication userApp = ApplicationRules.Instance.GetCurrentUserApplicationByUserIdAndType(userId, source);
            IEnumerable<Track> tracks = from t in m_DataContext.Tracks
                                        where t.UserApplication == userApp && t.TrackType == type && t.TrackDateTime.Date == DateTime.Now.Date
                                        select t;
            Track track = tracks.SingleOrDefault();
            if (track == null)
            {
                AddTrack(userApp, type, parameters);
            }
            else
            {
                string newContent = string.Join("#####", parameters);
                track.TrackContent = newContent;
                track.TrackDateTime = DateTime.Now;
                m_DataContext.SubmitChanges(ConflictMode.ContinueOnConflict);
            }
        }

        public void GetOnlineUser()
        {
            throw new NotImplementedException();
        }

        public void GetUserData(string userId)
        {
            throw new NotImplementedException();
        }

        public string GetUserHomepageLink(string userId)
        {
            return ApplicationSettings.HOMEPAGEURLTEMPLATE + userId;
        }

        public void SendMail(string to, string subject, string body, bool isBodyHtml)
        {
            MailMessage mail = new MailMessage();
            mail.To.Add(to);
            mail.Subject = subject;
            mail.Body = body;
            mail.IsBodyHtml = isBodyHtml;
            mail.From = new MailAddress("mmtestmail@sohu.com");
            SmtpClient client = new SmtpClient();
            client.Send(mail);
        }

        public void SendMessage()
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
